#include "MyServer.h"

int signalPipe[2];
void sigFunc(int signum)
{
    printf("signum = %d\n", signum);
    write(signalPipe[1], "exit", 4);
    printf("parent got signal\n");
}

int main(int argc, char *argv[])
{
    ARGS_CHECK(argc, 2);
    char str[128];
    unsigned long strSize = 128;

    // TCP监听
    int ret = getValInJSON("ip", argv[1], str, strSize);
    MYERROR_CHECK(ret, -1, "getValInJSON");
    char ip[15] = {0};
    strncpy(ip, str, strlen(str));
    ret = getValInJSON("port", argv[1], str, strSize);
    MYERROR_CHECK(ret, -1, "getValInJSON");
    char port[5] = {0};
    strncpy(port, str, strlen(str));
    int sockfd;
    tcplink(ip, port, &sockfd);

    

    // 初始化退出信号
    ret = pipe(signalPipe);
    ERROR_CHECK(ret, -1, "pipe");
    if (fork() != 0)
    {
        close(signalPipe[1]);
        signal(SIGUSR1, sigFunc);
        wait(NULL);//等待进程退出
        exit(0);
    }
    close(signalPipe[0]);

    // 初始化多线程
    threadPool_t threadPool;
    threadPoolInit(&threadPool, argv[1]);
    makeWorker(&threadPool);

    // epoll
    int epfd;
    epollInit(&epfd);
    epollAdd(epfd, sockfd);
    epollAdd(epfd, signalPipe[1]);
    struct epoll_event readyset[2] = {0};
    while (1)
    {
        int readynum = epoll_wait(epfd, readyset, 2, -1);
        for (int i = 0; i < readynum; i++)
        {
            if (readyset[i].data.fd == sockfd)
            {
                struct sockaddr_in addr;
                socklen_t addrlen=sizeof(addrlen);
                int netfd = accept(sockfd,(struct sockaddr *)&addr,&addrlen);
                ERROR_CHECK(netfd,-1,"accept");
                printf("链接建立成功->IP:%s %d\n",inet_ntoa(addr.sin_addr),ntohs(addr.sin_port));
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                EntaskQueue(&threadPool.taskQueue,netfd);
                puts("missions is enQueue!!");
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
                pthread_cond_signal(&threadPool.taskQueue.cond);
            }else if(readyset[i].data.fd == signalPipe[1]){
                printf("threadPool exit!\n");
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                threadPool.isexit = 1; // 修改退出标志位
                pthread_cond_broadcast(&threadPool.taskQueue.cond);//广播退出
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
                for (int i = 0; i < threadPool.threadNum; i++)//等待线程结束
                {
                    pthread_join(threadPool.tidArr[i],NULL);
                }
                mysql_close(threadPool.mysql);//关闭mysql
                puts("done");
                exit(0);
                
            }
        }
    }

    return 0;
}